<?php

namespace GoWithFood\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;

class GoWithFoodModel extends BaseModel {

    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['title', 'replaceBadWord', self::MODEL_BOTH, 'callback'],
    ];
    protected $_validate = [
        ['title', 'require', '内容不能为空'],
        ['user_id', 'require', '发布人不能为空'],
    ];
    protected $_scope = [
        'valid' => [
            'where' => ['audit' => 1, 'delete_time' => 0,'closed'=>0],
        ],
        'history' => [
            'where' => ['audit' => 1, 'delete_time' => 0],
        ]
    ];

    public function publish($uid, $data) {
        $data = array_filter($data);
        if (!empty($data['start_time'])) {
            $day = date("Y-m-d", $data['start_time']);
            $time = $day . ' ' . intval($data['hour']) . ':' . intval($data['minute']);
            $data['start_time'] = strtotime($time);
        }

        $post = [
            'user_id' => $uid,
            'sex' => $data['sex'],
            'who_show' => $data['who_show'],
            'type' => $data['type'],
            'start_time' => $data['start_time'],
            'hour' => $data['hour'],
            'minute' => $data['minute'],
            'end_time' => $data['end_time'],
            'lat' => $data['lat'],
            'lng' => $data['lng'],
            'adcode' => $data['adcode'],
            'citycode' => $data['citycode'],
            'city' => $data['city'],
            'district' => $data['district'],
            'street' => $data['street'],
            'mark' => $data['mark'],
            'audit' => 1, // 默认
            'is_ontime' => $data['is_ontime'],
            'poiname'=>$data['poiname'],
            'position' => $data['position'],
        ];

        $post = array_filter($post);


        $postModel = D('GoWithFood');
        $postModel->create($post);
        if ($data['id']) {
            $post['food_id'] = $data['id'];
            $postModel->save($post);
            return true;
        }
        if ($id = $postModel->add()) {
            return $id;
        } else {
            throw new ModelException(80001, $postModel->getError());
        }
    }

    public function autofill() {
        $config = C('sdk.oss');
        $posts = D('Post')->where(['type' => '2', 'is_transed' => 'N'])->select();
        foreach ($posts as $post) {
            $useCdn = strpos($post['video'], $config['cdn']) !== false;
            $mediaUrl = $useCdn ? str_replace($config['cdn'], "{$config['bucket']}.{$config['endpoint']}", $post['video']) : $post['video'];
            $media = M('Media')->getByUrl($mediaUrl);
            if ($media) {
                $post['cover_url'] = $media['cover_url'];
                $post['video'] = $media['trans_url'] ? : $media['url'];
                $post['is_transed'] = 'Y';
                M('Post')->save($post);
            }
        }
    }

    public function praise($postId, $userId) {
        $zan = D('PostZan')->where(['post_id' => $postId, 'user_id' => $userId])->find();
        if ($zan) {
            throw new ModelException(80002);
        }
        D('Post')->where(['post_id' => $postId])->setInc('zan_num', 1);
        D('PostZan')->add([
            'post_id' => $postId,
            'user_id' => $userId,
            'create_time' => time(),
            'create_ip' => get_client_ip(),
        ]);
        return true;
    }

    protected function _after_find(&$record, $options) {
        if(!empty($record['who_show'])){
               $record['who_show'] = explode(',',$record['who_show']);
               for($i=0;$i<count($record['who_show']);$i++){
                    $record['who_show'][$i] = (int)$record['who_show'][$i];
               }
           }
        $record['is_ontime'] = (int) $record['is_ontime'];
    }

    protected function _after_select(&$records, $options) {
        if (empty($records))
            return;

        foreach ($records as &$record) {
            if (!empty($record['who_show'])) {
                $record['who_show'] = explode(',', $record['who_show']);
                for ($i = 0; $i < count($record['who_show']); $i++) {
                    $record['who_show'][$i] = (int) $record['who_show'][$i];
                }
                $record['is_ontime'] = (int) $record['is_ontime'];
            }
        }
    }

    protected function implodeImage($images) {
        return $images ? implde(',', $images) : '';
    }

    /**
     * 过滤敏感词
     * @param string $data
     * @return string
     */
    protected function replaceBadWord($data) {
        $v = unserialize(D('Setting')->getByK('articlesensitivewords')['v']);
        $words = empty($v['word']) ? [] : explode('|', trim($v['word'], '|'));
        return filter_badwords($data, $words);
    }

}
